package cn.usian.service.impl;

import cn.usian.exception.JyzxException;
import cn.usian.jyzx.model.commot.RedisCommot;
import cn.usian.jyzx.model.dto.h5.UserLoginDto;
import cn.usian.jyzx.model.dto.h5.UserRegisterDto;
import cn.usian.jyzx.model.entity.user.UserAddress;
import cn.usian.jyzx.model.entity.user.UserInfo;
import cn.usian.jyzx.model.vo.common.Result;
import cn.usian.jyzx.model.vo.common.ResultCodeEnum;
import cn.usian.jyzx.model.vo.h5.UserInfoVo;
import cn.usian.mapper.UserMapper;
import cn.usian.service.UserService;
import cn.usian.utils.HttpUtils;
import cn.util.AuthThreadLocalUtils;
import com.alibaba.fastjson.JSON;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.http.HttpResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceimpl implements UserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    RedisTemplate<String,String> redisTemplate;

    @Override
    public void sendCode(String phone) {
        String randomCode = getRandom(phone);
        redisTemplate.boundValueOps(RedisCommot.RANDOM_CODE).set(randomCode,5, TimeUnit.MINUTES);
    }

    @Override
    public void userInfo(UserRegisterDto userRegisterDto) {
        String randomCode = redisTemplate.boundValueOps(RedisCommot.RANDOM_CODE).get();
        if (!randomCode.equals(userRegisterDto.getCode())){
            throw new JyzxException(ResultCodeEnum.VALIDATECODE_ERROR);
        }

        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(userRegisterDto,userInfo);
        userInfo.setPassword(DigestUtils.md5DigestAsHex(userRegisterDto.getPassword().getBytes()));
        userInfo.setNickName(userRegisterDto.getNickName());
        userInfo.setAvatar("https://img1.baidu.com/it/u=383247633,1986808664&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500");
        userInfo.setSex(1);
        userInfo.setPhone(userRegisterDto.getUsername());
        userMapper.insert(userInfo);
    }

    @Override
    public Result login(UserLoginDto userLoginDto) {
        UserInfo login = userMapper.login(userLoginDto);
        if (login==null){
            throw new JyzxException(ResultCodeEnum.LOGIN_ERROR);
        }
        String password = DigestUtils.md5DigestAsHex(userLoginDto.getPassword().getBytes());
        if (!login.getPassword().equals(password)){
            throw new JyzxException(ResultCodeEnum.LOGIN_ERROR);
        }
        String token= UUID.randomUUID().toString();
        redisTemplate.boundValueOps(token).set(JSON.toJSONString(login));
        return Result.build(token,ResultCodeEnum.SUCCESS);
    }

    @Override
    public Result<UserInfoVo> getCurrentUserInfo(HttpServletRequest request) {
        String token = request.getHeader("token");
        String tokenJson = redisTemplate.boundValueOps(token).get();
        UserInfo userInfos = JSON.parseObject(tokenJson, UserInfo.class);
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfos,userInfoVo);
        return Result.build(userInfoVo,ResultCodeEnum.SUCCESS);
    }

    @Override
    public Result<List<UserAddress>> findUserAddressList() {
        Long id = AuthThreadLocalUtils.get().getId();
        List<UserAddress> userAddresses= userMapper.findUserAddressList(id);
        return Result.build(userAddresses,ResultCodeEnum.SUCCESS);
    }


    public static String getRandom(String phone) {
        String host = "https://cxkjsms.market.alicloudapi.com";
        String path = "/chuangxinsms/dxjk";
        String method = "POST";
        String appcode = "851ce02924664c50b6fd03f4196b4b07";//开通服务后 买家中心-查看AppCode
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        String randomCode = RandomStringUtils.randomNumeric(4);
        querys.put("content", "【创信】你的验证码是："+randomCode+"，3分钟内有效！");

        querys.put("mobile", phone);
        Map<String, String> bodys = new HashMap<String, String>();


        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            System.out.println(response.toString());
            //获取response的body
            //System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return randomCode;
    }
}
